from datetime import datetime
import backtrader as bt
import pandas as pd
from data_feed import StockDataFetcher, MyStockData, etf_daily
from MyStrategy import SmaCross, BacktestConfig

symbol="512880"
adjust = "hfq"
start_date = datetime(2022, 10, 1)
end_date = datetime.now()
pfast=1
pslow=20
start_cash=50000
commission=0.002
slippage=0.005

# =============create a "Cerebro" engine instance==========
cerebro = bt.Cerebro()  
# =============添加etf数据源  ===================================
etf_fetcher = etf_daily(symbol=symbol,adjust=adjust) # 抓取股票行情类实例化
data_stock = etf_fetcher.get_data()          # 对象的获取数据方法
data = MyStockData(dataname=data_stock, fromdate=start_date, todate=end_date) # 实例数据源 
cerebro.adddata(data, name=symbol)  # Add the data feed
# ==============添加策略========================================
cerebro.addstrategy(SmaCross, pfast=pfast, pslow=pslow)  # Add the trading strategy, 设置均线参数

# ==============置投资金额,佣金,分析及打印分析结果)===============
config = BacktestConfig(start_cash=start_cash, commission=commission, slippage=slippage)   #建立类(设置投资金额,佣金,分析及打印分析结果)
config.setup(cerebro)       #设置投资金额,佣金,分析

results = cerebro.run()  # run it all

config.print_results(cerebro, results, start_date, end_date) # 打印分析结果
config.excel_results(cerebro, results, start_date, end_date) # 买卖与分析输出到excel
#=====================================================================================

cerebro.plot()  # and plot it with a single command